let globalUserId;

document.addEventListener('DOMContentLoaded', function () {
    if (!username) {
        alert('Пожалуйста, войдите в систему для доступа к профилю.');
        window.location.href = '/login.php';
        return;
    }
    loadProfile(username);
});

function loadProfile(username) {
    fetch(`/DAO/user_DAO.php?action=getUserByUsername&username=${encodeURIComponent(username)}`)
        .then(response => response.json())
        .then(data => {
            if (!data || data.error) {
                throw new Error(data.error || 'Пользователь не найден.');
            }
            displayProfile(data);
            return fetch(`/DAO/user_DAO.php?action=getUserIdByUsername&username=${encodeURIComponent(username)}`);
        })
        .then(response => response.json())
        .then(userIdData => {
            if (userIdData && userIdData.id) {
                globalUserId = userIdData.id;
                loadAddresses();
                loadOrders();
            } else {
                throw new Error('ID пользователя не найден.');
            }
        })
        .catch(error => {
            alert(`Ошибка загрузки профиля пользователя: ${error.message}`);
            window.location.href = '/login.php';
        });
}

function loadAddresses() {
    if (!globalUserId) {
        alert('ID пользователя не определен.');
        window.location.href = '/login.php';
        return;
    }

    fetch(`/DAO/user_address_DAO.php?action=getUserAddressesByUserIdJson&userId=${globalUserId}`)
        .then(response => response.json())
        .then(data => {
            const tableBody = document.getElementById('addressTable').querySelector('tbody');
            tableBody.innerHTML = '';
            data.forEach(address => {
                const row = tableBody.insertRow();
                row.insertCell(0).textContent = address.id;
                row.insertCell(1).textContent = address.address;
                const actionsCell = row.insertCell(2);
                actionsCell.innerHTML = `<i class="fas fa-edit" style="color: blue; cursor: pointer;" onclick='openEditAddressModal(${JSON.stringify(address)})'></i>
                    <i class="fas fa-trash-alt" style="color: red; margin-left: 10px; cursor: pointer;" onclick="deleteAddress(${address.id})"></i>`;
            });
        })
        .catch(error => console.error('Ошибка при загрузке адресов:', error));
}

function deleteAddress(addressId) {
    if (confirm('Вы уверены, что хотите удалить этот адрес? ID: ' + addressId)) {
        fetch('/DAO/user_address_DAO.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: 'action=deleteUserAddress&id=' + addressId
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert(data.message);
                    loadAddresses();
                } else {
                    alert('Ошибка: ' + data.message);
                }
            })
            .catch(error => {
                console.error('Ошибка при удалении адреса:', error);
            });
    }
}

function displayProfile(userData) {
    document.getElementById('username').textContent = userData.username;
    document.getElementById('email').textContent = userData.email || 'Не указан';
    document.getElementById('phone').textContent = userData.phone || 'Не указан';
    const avatarEl = document.querySelector('.profile-photo img');
    avatarEl.src = userData.avatar_url || '/images/users/default.png';
}

function openAddAddressModal() {
    document.getElementById('addressId').value = '';
    document.getElementById('addressInput').value = '';
    document.getElementById('modalAddressTitle').textContent = 'Добавить новый адрес';
    document.getElementById('addressModal').style.display = 'block';
}

function openEditAddressModal(address) {
    document.getElementById('addressId').value = address.id;
    document.getElementById('addressInput').value = address.address;
    document.getElementById('modalAddressTitle').textContent = 'Редактировать адрес';
    document.getElementById('addressModal').style.display = 'block';
}

document.getElementById('addressForm').addEventListener('submit', function (event) {
    event.preventDefault();
    const formData = new FormData(this);
    const addressId = formData.get('addressId');
    const action = addressId ? 'updateExistingUserAddress' : 'addNewUserAddress';
    formData.append('action', action);

    if (addressId) {
        formData.append('id', addressId);
    }
    formData.append('user_id', globalUserId);

    fetch('/DAO/user_address_DAO.php', {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            alert(data.message);
            if (data.success) {
                closeAddressModal();
                loadAddresses();
            }
        })
        .catch(error => {
            console.error('Ошибка при сохранении адреса:', error);
            closeAddressModal();
        });
});

function closeAddressModal() {
    document.getElementById('addressModal').style.display = 'none';
}

document.querySelector('.edit-profile-btn').addEventListener('click', function () {
    document.getElementById('editUsername').value = document.getElementById('username').textContent;
    document.getElementById('editEmail').value = document.getElementById('email').textContent;
    document.getElementById('editPhone').value = document.getElementById('phone').textContent;
    openUserModal();
});

function openUserModal() {
    document.getElementById('editProfileModal').style.display = 'block';
}

function closeUserModal() {
    document.getElementById('editProfileModal').style.display = 'none';
}

document.getElementById('avatar_file').addEventListener('change', function() {
    var fileLabel = document.getElementById('file-chosen');
    if (this.files.length > 0) {
        fileLabel.textContent = this.files[0].name;
    } else {
        fileLabel.textContent = 'Нет файла';
    }
});

document.getElementById('editProfileForm').addEventListener('submit', function(event) {
    event.preventDefault();
    const formData = new FormData(this);
    const fileInput = document.getElementById('avatar_file');
    if (fileInput.files.length > 0) {
        formData.append('avatar_file', fileInput.files[0]);
    }
    formData.append('action', 'updateProfile'); 
    formData.append('id', globalUserId);
    formData.append('username', document.getElementById('editUsername').value);
    formData.append('phone', document.getElementById('editPhone').value);
    formData.append('email', document.getElementById('editEmail').value);

    fetch('/DAO/user_DAO.php', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        alert(data.message);
        if (data.success) {
            closeUserModal();
            loadProfile(username); 
        }
    })
    .catch(error => {
        console.error('Ошибка при обновлении профиля:', error);
        closeUserModal();
    });
});

function loadOrders() {
    if (!globalUserId) {
        console.error('ID пользователя не определен.');
        return;
    }

    fetch(`/DAO/order_DAO.php?action=getAllOrdersByUserIdJson&userId=${globalUserId}`)
        .then(response => response.json())
        .then(data => {
            const tableBody = document.getElementById('orderTable').querySelector('tbody');
            tableBody.innerHTML = '';
            data.forEach(order => {
                const row = tableBody.insertRow();
                row.insertCell(0).textContent = order.id;
                row.insertCell(1).textContent = order.order_date;
                row.insertCell(2).textContent = order.status;
                row.addEventListener('click', () => displayOrderDetails(order));
            });
        })
        .catch(error => console.error('Ошибка при загрузке заказов:', error));
}

function displayOrderDetails(order) {
    document.getElementById('detailOrderId').textContent = order.id;
    document.getElementById('detailOrderDate').textContent = order.order_date;
    document.getElementById('detailOrderStatus').textContent = order.status;
    document.getElementById('detailOrderTotalPrice').textContent = order.total_price;
    document.getElementById('detailOrderAddress').textContent = order.delivery_address;

    fetch(`/DAO/order_details_DAO.php?action=getAllOrderDetailsByOrderIdJson&orderId=${order.id}`)
        .then(response => response.json())
        .then(items => {
            const itemsList = document.getElementById('orderItemsList');
            itemsList.innerHTML = ''; 
            items.forEach(item => {
                fetchProductDetails(item.product_id, item.quantity, item.price_per_item);
            });
            document.getElementById('orderDetailsModal').style.display = 'block';
        })
        .catch(error => console.error('Ошибка при загрузке деталей состава заказа:', error));
}

function fetchProductDetails(productId, quantity, pricePerItem) {
    fetch(`/DAO/product_DAO.php?action=getProductById&id=${productId}`)
        .then(response => response.json())
        .then(product => {
            const itemsList = document.getElementById('orderItemsList');
            let li = document.createElement('li');
            li.innerHTML = `
                <img src="${product.image_url}" alt="${product.name}" style="width:50px; height:50px; object-fit:cover; margin-right:10px;">
                <strong>${product.name}</strong> - Количество: ${quantity}, Цена за единицу: ${pricePerItem} руб.`;
            itemsList.appendChild(li);
        })
        .catch(error => console.error('Ошибка при загрузке информации о товаре:', error));
}

function closeOrderModal() {
    document.getElementById('orderDetailsModal').style.display = 'none';
}

